In C, a function is a block of code that performs a specific task and can be called from other parts of the program. Functions help in breaking down complex tasks into smaller, manageable parts, making code more organized and easier to maintain. Functions in C can have a return type (indicating the type of value they return) and can accept zero or more input parameters.
To declare and define a function in C, specify its return type, name, and the list of parameters (if any). The function's implementation is enclosed in curly braces {}.
return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, ...) {
// Function implementation
// ...
return return_value; // (Only if the function has a return type)
}
#include <stdio.h>
// Function to calculate the sum of two integers
int add(int a, int b) {
return a + b;
}
// Function to find the maximum of two integers
int findMax(int x, int y) {
return (x > y) ? x : y;
}
// Function to print a message n times
void printMessage(int n) {
for (int i = 0; i < n; i++) {
printf("Hello, world! %d\n", i + 1);
}
}
int main() {
int num1 = 10, num2 = 20;
// Call the add function and store the result in 'sum'
int sum = add(num1, num2);
printf("Sum: %d\n", sum);
// Call the findMax function and print the result
int max = findMax(num1, num2);’
printf("Max: %d\n", max);
// Call the printMessage function
printMessage(3);
return 0;
}
Sum: 30
Max: 20
Hello, world! 1
Hello, world! 2
Hello, world! 3
What is a function in C?
What is the keyword used to define a function in C?
What is the return type of a function that doesn't return any value in C?
What is used to call a function in C?
What is a function that calls itself in C?